local Partner = class("PartnerEquip")
local PartnerSkill = import(".PartnerSkill")
local PartnerHelper = require("app.partner.PartnerHelper")

function Partner:ctor()
    self._isHave = false -- 是否拥有
    self._lv = 1 -- 等级
    self._exp = 0 -- 当前经验
    self._equips = {} -- 装备
    self._skills = {} -- 技能
    self._combatPower = 0 -- 战力
    self._isNew = false
    self._shareData = nil
    self._isEquiped = false
    self._raceId = -1
    self.itemBagType = Enums.ItemBagType.partner
    self.showType = Enums.ItemShowType.partner
    self._duration = 0
    self._quality = 1 --先默认写一下品质
    self._maxQuality = 1
end

function Partner:initWithConf(conf)
    assert(conf ~= nil, " init Partner conf is nil")
    self._conf = conf
    self._id = tonumber(conf.ID)
    self._star = tonumber(self._conf.initialStar)
    self._raceId = tonumber(self._conf.raceID)
    self._qualitypropConf = GD:queryPartnerQualityPropById(self._id)
    self._maxQuality = tonumber(self._qualitypropConf.maxRank or 5)
end

function Partner:initWithId(id)
    assert(id ~= nil, " init Partner id is nil")
    self._conf = GD:queryPartnerById(id)
    self._id = id
    self._star = tonumber(self._conf.initialStar)
    self._raceId = tonumber(self._conf.raceID)
    self._qualitypropConf = GD:queryPartnerQualityPropById(self._id)
    self._maxQuality = tonumber(self._qualitypropConf.maxRank or 5)
end

function Partner:initWithBaseInfo(baseInfo)  
    self._conf = GD:queryPartnerById(baseInfo.ID)
    assert(self._conf ~= nil, " initWithBaseInfo conf is nil")
    self._id = baseInfo.ID
    self._star = tonumber(self._conf.initialStar)
    self._raceId = baseInfo.RaceId
    self._quality = baseInfo.Quality
    self._lv = baseInfo.Lv
    self._combatPower = baseInfo.CombatPower
    self._qualitypropConf = GD:queryPartnerQualityPropById(self._id)
    self._maxQuality = tonumber(self._qualitypropConf.maxRank or 5)
end

function Partner:initSkill()
    local rows = GD:queryPartnerSkillsByPartnerId(self._id)
    for k ,v in ipairs(rows) do
        local skill = PartnerSkill.new()
        skill:initByConf(v)
        self._skills[skill:getSlot()] = skill
        if self:isSpReward() then
            skill:setDisableUpgrade(true)
        end
    end
end

function Partner:addEquip(equip)
    assert(equip ~= nil, "addEquip  equip is nil")
    equip:setPartner(self)
    self._equips[equip:getSlot()] = equip
end

function Partner:read(value)
    self._lv = value.Lv -- 等级
    self._exp = value.Exp -- 当前经验
    self._raceId = value.RaceID -- 当前经验
    self._star = value.Star
    self._quality = value.Quality
    local oldCombatPower = self._combatPower
    self._combatPower = value.combatPower

    if oldCombatPower ~= 0 then
        self._diffCombatPower = self._combatPower - oldCombatPower
    end
    
    for k,v in pairs(value.Skills) do
        local skill = self._skills[v.Sort]
        if skill then
            skill:setUnlock(true)
            skill:setSkillId(v.SkillID)
        end
    end

    for k,v in pairs(value.Equips) do
        local equip = self._equips[v.Sort]
        if equip then
            equip:setUnlock(true)
            equip:updateData(v)
        end
    end
end

function Partner:getDiffCombatPower()
    local diff = self._diffCombatPower or 0
    return diff
end

function Partner:cleanDiffCombatPower()
    self._diffCombatPower = 0
end

-- 清除一下 缓存数据
function Partner:cleanTempData()
    for k, v in pairs(self._equips) do
        v:setNewUnlock(nil)
    end
    self._isNew = false
    self._diffCombatPower = 0 
end

function Partner:setIsHave(trueOrFalse)
    self._isHave = trueOrFalse
end
function Partner:isHave()
    if self._isHave then
        if self:isSpReward() and self._duration > 0 and self._duration < app.session:getServerTime() then
            return false
        end
        return true
    end
   
    return false
end

function Partner:getName()
    return L(self._conf.name)
end


function Partner:getDesc()
    return L(self._conf.desc)
end

function Partner:getResource()
    local resource = GD:getConvertResource(self._conf.getResource, Enums.ItemBagType.item, tonumber(self._conf.itemID))
	return resource
end

-- 判断是否可以升级
function Partner:canUpgrade()
    return self._conf.type2 ~= "1"
end

-- 是否是 金腰带
function Partner:isSpReward()
    return self._conf.type2 == "1"
end

--可激活
function Partner:canActive()
    if not self:isHave() then
        --判断灵魂石数量
        local haveSoulNums = UD:getPartnerSoulCountById(self:getSoulStoneId())
        local needNums = self:getComposeNeedNum()
        if haveSoulNums >= needNums then
            return true
        end
    end

    return false
end

function Partner:canLvQuality()
    if self:isHave() and not self:isMaxQuality() then
        --判断灵魂石数量
        local haveSoulNums,needNums = self:getQualityCostNum()
        if haveSoulNums >= needNums then
            return true
        end
    end

    return false
end

-- 金腰带 icon
function Partner:getType2IconPath()
    if self._conf.type2icon and self._conf.type2icon ~= "" then
        return string.format("%s%s.png",Res.commonUIPath,self._conf.type2icon)
    end
end

function Partner:getIcon()
    return GD:getImagePath(Res.partnerIconPath, self._conf.icon)
end

function Partner:getJobIcon()
    return GD:getImagePath(Res.classIconPath,self._conf.jobicon)
end

function Partner:getIconBg()
    local quality = self:getQuality()
    if quality == 1 then
        return Res.Qulity_Icon_Bg[1]
    elseif quality == 2 then
        return Res.Qulity_Icon_Bg[2]
    elseif quality >= 3 and quality <= 4 then
        return Res.Qulity_Icon_Bg[3]
    elseif quality >= 5 and quality <= 7 then
        return Res.Qulity_Icon_Bg[4]
    elseif quality >= 8 and quality <= 11 then
        return Res.Qulity_Icon_Bg[5]
    else
        return Res.Qulity_Icon_Bg[6]
    end
end

function Partner:getJobName()
	return L(self._conf.job)
end

function Partner:getPartnerPosotionIconPath()
    return GD:getImagePath(Res.positionPath,self._conf.position)
end

-- 排序
function Partner:getSortIndex()
    return tonumber(self._conf.sort)
end

-- 获取展示动作
function Partner:getShowActions()
    local actions = string.split(self._conf.showAct, ";")
    return actions
end

--
function Partner:getRelationNum()
    return self._conf.relationNum
end

function Partner:setCombatPower( value )
    self._combatPower = value
end
--
function Partner:getQuality()
    --return PartnerHelper.getPartnerQualityByFightNum(self._combatPower)
    return self._quality or 1
end


function Partner:getSort()
    return tonumber(self._conf.sort)
end

function Partner:getConf()
    return self._conf
end

function Partner:getId()
    return self._id
end


function Partner:getStar()
    return self._star
end

function Partner:getCombatPower()
    return self._combatPower or 0
end

function Partner:setNew(b)
    self._isNew = b
end

function Partner:isNew()
    return self._isNew
end

function Partner:getClassId()
    return self._conf.classID
end

function Partner:setLevel(lv)
    self._lv = lv
end

function Partner:getLevel()
    return self._lv
end

function Partner:getExp()
    return self._exp
end

function Partner:getEquips()
    return self._equips
end

function Partner:getSkills()
    return self._skills
end

function Partner:getTypeName()
	if self._conf.typeDesc then
		return L(self._conf.typeDesc)
	end
	return L(Res.showTypeName .. self.showType)
end



function Partner:setShareData(shareData)
    self._shareData = shareData
end


function Partner:getShareData()
    return self._shareData
end


function Partner:isEquiped()
    return self._isEquiped
end

function Partner:setEquiped(trueOrFalse)
    self._isEquiped = trueOrFalse
end

function Partner:setRaceId(raceId)
    self._raceId = raceId
end

function Partner:isClassAvatarEnable()
    return true, {type=Enums.AvatarPreviewType.partner, data = self}
end

function Partner:getShowAvatorParams()
    local raceID = self._raceId
    if raceID == -1 then
        raceID = tonumber(self._conf.raceID)
    end
    return {
        dbArmatureInBattle = self._conf.dbArmatureInBattle,
        dbArmature = self._conf.dbArmature,
        gender = tonumber(self._conf.gender),
        classID = tonumber(self._conf.classID),
        raceID = raceID,
    }
end

function Partner:getTipsIcon()
	if not self._tipsIcon then
       self._tipsIcon = string.format("%s%s_s.png", Res.partnerIconPath, self._conf.icon)
    end
    return self._tipsIcon
end

function Partner:getRelationNum()
    return tonumber(self._conf.relationNum)
end


function Partner:getQualityColor()
    local queryConfigs = GD:queryPartnetQualityConfig()
    local qualityConf = queryConfigs[self:getQuality()]
    local colorStr = string.split(qualityConf.qualityStringColor,"#")
    local color = cc.c4b(checknumber(colorStr[1]),checknumber(colorStr[2]),checknumber(colorStr[3]),checknumber(colorStr[4]))

    return color
end

function Partner:getQualityText()
    local queryConfigs = GD:queryPartnetQualityConfig()
    local qualityConf = queryConfigs[self:getQuality()]
    return L(qualityConf.qualityString)
end

function Partner:getQualityImgPath()
    local queryConfigs = GD:queryPartnetQualityConfig()
    local qualityConf = queryConfigs[self:getQuality()]
    return string.format("art/partner/%s.png",qualityConf.qualityIcon)
end

function Partner:setDuration(dt)
    self._duration = dt
end

function Partner:getDuration()
    return self._duration
end

function Partner:isShow()
    return tonumber(self._conf.isShow) == 1
end

function Partner:getScale()
    return (tonumber(self._conf.size or 100) or 100)/100.0
end

function Partner:dump()
    local t = {
        name = self:getName(),
        _id = self._id,
        _isHave = self._isHave,
        _lv = self._lv,
        _exp = self._exp,
        _combatPower = self._combatPower,
        _equips = {},
        _skills = {}
        }   
    for k ,v in pairs(self._skills) do
        table.insert( t._skills, v:getDumpTable())
       
    end
    for k ,v in pairs(self._equips) do
        table.insert( t._equips, v:getDumpTable())
    end
    dump(t)
end

--获取partner升级品质后给玩家增加的属性
function Partner:getPlayerQualityPropShow()
    if not self._qualityPlayerProps then
        local parseStr = self._qualitypropConf[string.format("attrShow_%d",UD.player.classID)]
        local qProps = string.split(parseStr, ";")

        local p = {}
        for k, v in pairs(qProps) do
            local tempArr = string.split(v, "|")
            if #tempArr >= 2 then
                local props = {}
                for i =2, #tempArr do
                    local spArr = string.split(tempArr[i], "#")
                    table.insert(props, {spArr[1], tonumber(spArr[2])})
                end
                p[tonumber(tempArr[1])] = props
            else
                print("error ====>>> ", self._id, parseStr)
            end
        end
        self._qualityPlayerProps = p
    end
    return self._qualityPlayerProps
end

function Partner:getShowPlayerProps(q)
    if not q then
        q = self:getQuality()
    end
    return self:getPlayerQualityPropShow()[q] or {}
end

function Partner:getPartnerPropShow()
    if not self._qualityPartnerProps then
        local parseStr = self._qualitypropConf.partnerQualityProp
        local qProps = string.split(parseStr, ";")

        local p = {}
        for k, v in pairs(qProps) do
            local tempArr = string.split(v, "|")
            if #tempArr >= 2 then
                local props = {}
                for i =2, #tempArr do
                    local spArr = string.split(tempArr[i], "#")
                    table.insert(props, {spArr[1], tonumber(spArr[2])})
                end
                p[tonumber(tempArr[1])] = props
            else
                print("error ====>>> ", self._id, parseStr)
            end
        end
        self._qualityPartnerProps = p
    end
    return self._qualityPartnerProps
end

--获取升级品质需要的灵魂石数量
function Partner:getQualityCostNum()
    local itemId = checknumber(self._qualitypropConf.soulID)
    local haveNum = UD:getPartnerSoulCountById(itemId)
    local needNum = 0
    if self._isHave then
        if self._qualitypropConf.qualityUpdate == "0" then
            needNum = 0
        else
            if not self._qualityUpAry then
                local ary = string.splitTwice(self._qualitypropConf.qualityUpdate, nil, true)
                local ret = {}
                for i,v in ipairs(ary) do
                    ret[v[1]] = v[2]
                end
                self._qualityUpAry = ret
            end
            needNum = self._qualityUpAry[self._quality]
        end
    else
        needNum = tonumber(self._qualitypropConf.composeFragment)
    end
    --print("getQualityCostNum haveNum, needNum", haveNum, needNum,self._quality)
    return haveNum, needNum
end

function Partner:getSoulStoneId()
    return checknumber(self._qualitypropConf.soulID)
end

--获取合成需要的数量
function Partner:getComposeNeedNum()
    return checknumber(self._qualitypropConf.composeFragment)
end

function Partner:isMaxQuality()
    return self._maxQuality == self._quality
end

function Partner:checkQualityCostItemsEnough()
    local haveNum, needNum = self:getQualityCostNum()
    local isMaxQuality = self:isMaxQuality()
    return not isMaxQuality and haveNum >= needNum
end

return Partner